package com.mmall.concurrency.example.lock;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mmall.concurrency.example.atomic.AtomicExample3;

@Slf4j
public class LockExample6 {
	private static Logger log = LoggerFactory.getLogger(AtomicExample3.class);

    public static void main(String[] args) {
        ReentrantLock reentrantLock = new ReentrantLock();
        Condition condition = reentrantLock.newCondition();

        new Thread(() -> { // 线程1
            try {
                reentrantLock.lock(); // 加入了AQS等待队列
                log.info("wait signal"); // 1
                condition.await(); // 从AQS队列里移除， 对应的操作是锁的释放， 加入condition的等待队列
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // 线程1呗唤醒继续这里执行
            log.info("get signal"); // 4
            reentrantLock.unlock();
        }).start();

        new Thread(() -> { // 线程2
            reentrantLock.lock(); // 获得锁 加入了AQS等待队列
            log.info("get lock"); // 2
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            condition.signalAll(); // 线程1进入AQS，但是没有获得锁
            log.info("send signal ~ "); // 3
            reentrantLock.unlock(); // 释放锁
        }).start();
    }
}
